import React, {useEffect, useRef, useState} from 'react';
import {Form, Input, Select, PageHeader, Button, notification} from "antd";
import axios from "axios";
import style from "./NewsAdd.module.css";
import NewsEditor from "../../../components/news-manage/NewsEditor";

const {Option} = Select;

export default function NewsUpdate(props) {
    const [categories, setCategories] = useState([])
    const [newsContent, setNewsContent] = useState('')
    const [newsHeaderInfo, setNewsHeaderInfo] = useState(null);

    useEffect(() => {
        // console.log(props.match.params.id)
        axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
            // console.log(res.data.content)
            setNewsContent(res.data.content)

            // 设置表单初始值
            const {title, categoryId} = res.data
            newsForm.current.setFieldsValue({
                title,
                categoryId
            })
        })
        axios.get('/categories').then(res => {
            // console.log(res.data)
            setCategories(res.data)
        })
    }, [props.match.params.id])

    const newsForm = useRef(null)

    const validationForm = () => {
        // 校验新闻标题和分类
        newsForm.current.validateFields().then(res => {
            // console.log(res)
            // 将新闻标题和分类存储
            setNewsHeaderInfo(res)
        })
    }

    const handleLastStep = (auditState) => {
        // 重新补丁式上传更新内容
        axios.patch(`/news/${props.match.params.id}`, {
            ...newsHeaderInfo,
            "content": newsContent,
            "auditState": auditState,
        }).then(() => {
            // 通知成功
            notification.success({
                message: '恭喜您！',
                description:
                    auditState === 0 ? '保存草稿成功，您可以在【新闻管理/草稿箱】中查看' : '提交审核成功，您可以在【新闻管理/审核列表】中查看',
            });
            // 跳转到相应页面
            props.history.push(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
        })
    }

    return (
        <div>
            {newsContent && <div>
                <PageHeader
                    ghost={false}
                    onBack={() => window.history.back()}   // => props.history.goBack()
                    title='更新新闻'
                />
                {/* 标题和分类 */}
                <div style={{width: '95%', margin: '0 auto'}} onBlur={() => validationForm()}>
                    <Form
                        ref={newsForm}
                        name="basic"
                        autoComplete="off"
                    >
                        <Form.Item
                            label="新闻标题"
                            name="title"
                            rules={[{required: true, message: '请输入新闻标题'}]}
                        >
                            <Input/>
                        </Form.Item>

                        <Form.Item
                            label="新闻分类"
                            name="categoryId"
                            rules={[{required: true, message: '请选择新闻分类'}]}
                        >
                            <Select>
                                {categories.map(item =>
                                    <Option value={item.id} key={item.id}>{item.title}</Option>
                                )}
                            </Select>
                        </Form.Item>
                    </Form>
                </div>
                {/* 编辑器 */}
                <div>
                    <NewsEditor getEditorContent={(value) => {
                        console.log(value)
                        // 将新闻内容储存起来
                        if(value){
                            setNewsContent(value)
                        }
                    }} content={newsContent}/>
                </div>
                <div className={style.btn}>
                    <Button type="primary" onClick={() => handleLastStep(0)}>保存草稿</Button>
                    <Button className={style.audit} type='primary' onClick={() => handleLastStep(1)}>提交审核</Button>
                </div>
            </div>}
        </div>
    )
}